package web.controller;

import web.services.*;
import web.util.DateUtil;
import web.util.DownloadUtil;
import web.util.StringOperateUtil;
import web.util.email.EmailUtil;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import test.util.PathUtil;

import javax.servlet.http.HttpServletRequest;
import java.util.*;


/**
 * Created by Administrator on 2016/9/5.
 */
@Controller
@RequestMapping("admin")
public class AdminController {
    @Autowired
    private LuceneSearchService luceneSearchService;
    @Autowired
    private ToolService toolService;
    @Autowired
    private LocationService locationService;
    @Autowired
    private AdminService adminService;
    @Autowired
    private SearchService searchService;

    private final static Logger LOGGER = LoggerFactory.getLogger(AdminController.class);

    @RequestMapping("")
    public String index(){
        return "redirect:/admin/news";

    }

    @RequestMapping("news")
    public String news(Model model,HttpServletRequest request,
            @RequestParam(required =false,value="orderKey", defaultValue ="") String orderKey,
            @RequestParam(required = false,value = "key" , defaultValue = "") String key,
            @RequestParam(required = false,value = "time" , defaultValue = "0") int time,
            @RequestParam(required = false,value = "province" , defaultValue = "0") String province,
            @RequestParam(required = false,value = "num" , defaultValue = "500") int num,
            //下载excel参数判断，0不下载，1下载，toAddress
            @RequestParam(required = false,value = "excelType" , defaultValue = "0") int excelType,
            @RequestParam(required = false,value = "sendExcelType" , defaultValue = "0") int sendExcelType,
            @RequestParam(required = false,value = "toAddress" , defaultValue = "") String toAddress
    ){
        LOGGER.info("开始[一键通]数据搜索-");
        model.addAttribute("orderKey", orderKey);
        model.addAttribute("key", key);
        model.addAttribute("time",time);
        model.addAttribute("province",province);
        model.addAttribute("title","新一键通");
        model.addAttribute("status","1");
        model.addAttribute("toAddress",toAddress);
        model.addAttribute("sendExcelType",sendExcelType);
        model.addAttribute("excelType",excelType);
        String timeStr=time==0?"不限时间":time+"月以内";
        //获取省份
        List<Map<String,Object>> locationList=locationService.getLocationAllList();
        model.addAttribute("locationList",locationList);

        if(time != 0)time = DateUtil.getNowToInt() - (60 * 60 * 24 * 30 * time);
//        通过搜索条件查询所有招标信息
        List<Map<String,Object>> list=luceneSearchService.search(key+" "+orderKey,province,time+"",num);
        for(Map<String,Object> m:list){
            m.put("content","");
            m.put("title",StringOperateUtil.reStrings(m.get("title")+""));
            m.put("subscriber",StringOperateUtil.reStringsYh(m.get("subscriber")+""));
        }
        //model.addAttribute("list",list);
        model.addAttribute("listJson",JSONObject.toJSONString(list));
        model.addAttribute("maxPage",list.size()%50==0 ? list.size()/50 : list.size()/50+1 );

//        存储招标单位，用于去重
        Set<String> set= new HashSet<String>();
//        通过招标单位
        Map<String,List<String>> newsMap =new HashMap<String, List<String>>();
//        中标联系方式
        Map<String,Map<String,Object>> mapSuccessContact=new HashMap<String, Map<String, Object>>();
//        遍历招标信息获取其他信息
        for (Map<String,Object> mapNews : list) {
            String subscriber=mapNews.get("subscriber").toString();
            if(set.contains(subscriber))continue;

//            通过招标单位查询所有中标单位
            List<Map<String,Object>> listWinBidCompanys=toolService.findWinBidCompanyBySubscriberNews(subscriber);
            List<String> listWinBidCompany =new ArrayList<String>();
            for (Map<String, Object> winBidCompany : listWinBidCompanys) {
                listWinBidCompany.add(winBidCompany.get("winBidCompany").toString());
            }
            newsMap.put(subscriber, listWinBidCompany);
            set.add(subscriber);
//            通过中标单位查询所有中标联系方式
            for (Map<String,Object> s : listWinBidCompanys) {
                mapSuccessContact.put(s.get("winBidCompany").toString(), searchService.findSuccessfulNewsBySubscriber(s,excelType));
            }
        }
        model.addAttribute("mapSuccessContact",JSONObject.toJSONString(mapSuccessContact));
        model.addAttribute("newsMap", JSONObject.toJSONString(newsMap));
        LOGGER.info("-查询数据完成-");

        /* excel下载判断,为1时下载 */
        if(list.size()>0){
            /* 文件保存路径 */
            String xlsName=DateUtil.getStringDate((int)(new Date().getTime()/1000),"yyyyMMddHHmmss");
            String keyStr=(orderKey+" "+key).trim().replaceAll(" ", "-");
            String provinceStr="";
            if("0".equals(province)){
                provinceStr="不限地域";
            }else{
                provinceStr=locationService.getLocationMap().get(province+"")+"";
            }
            String excelName=keyStr+"-"+timeStr+"-"+provinceStr+"-"+xlsName+"-"+excelType;
            String path="";
            String url="";
//            if("0:0:0:0:0:0:0:1".equals(request.getRemoteAddr())){
                //本地下载
//                path="C:/Users/Administrator/Desktop/download/";
//                url=path+excelName+"YJT.xls";
//                LOGGER.info("-start-【本地访问】创建excel-");
//            }else{
                path= PathUtil.getInstance().getWebInfPath().replaceAll("/WEB-INF","")+"download\\";
                 url=request.getRequestURL().toString().replaceAll("/admin/news","/download/"+excelName+"YJT.xls");
                LOGGER.info("-start-创建excel-");
//            }

            /* 生成excel */
            DownloadUtil.getExcelYJT(key+" "+orderKey,list,newsMap,mapSuccessContact,path+excelName+"YJT.xls");
//            String url=request.getRequestURL().toString().replaceAll("/admin/news","/download/"+excelName+"YJT.xls");
            model.addAttribute("excelUrl",url);
            LOGGER.info("-end-创建excel-");
        }

        return "document/views/baidu/admin/newsAdmin";
    }

    @RequestMapping("forecast")
    public String forecast(Model model,
                           @RequestParam(required =false,value="key", defaultValue ="") String key){

        model.addAttribute("title","前序关键词");
        model.addAttribute("status","2");
        model.addAttribute("key",key);
//        通过关键词获取前序关键
        List<Map<String,Object>> list = adminService.forecastService(key);
        model.addAttribute("list",list);
        return "document/views/baidu/admin/keyAdmin";
    }


    /**
     * 发送邮件
     * @param excelUrl url路径
     * @param toEmail
     * @return
     */
    @RequestMapping("sendEmail")
    @ResponseBody
    public Map<String,Object> sendEmail(HttpServletRequest request,String excelUrl,String toEmail){
        LOGGER.info("-一键通邮件发送-");
        Map<String,Object> map=new HashMap<String, Object>();
        String content="";
        String emailTitle="招标猫一键通搜索结果：见附件";
        String p1=excelUrl.substring(excelUrl.indexOf("download"));
        String p2=PathUtil.getInstance().getWebInfPath().replaceAll("/WEB-INF","");
        String filePath="";
//        if("0:0:0:0:0:0:0:1".equals(request.getRemoteAddr())){
//            filePath="E:\\IntelliJ_workspace\\xm\\baidumao\\src\\main\\webapp\\"+p1;
//            filePath="C:/Users/Administrator/Desktop/"+p1;
//        }else{
            filePath=p2+p1;
//        }
        boolean bool=EmailUtil.sendEmailFJ(content,toEmail,emailTitle,filePath);

        map.put("rs",bool?"1":"0");
        return map;
    }






}
